const base = '';
let PAGE = 1;

// 注册
const registary = {
    // 获取表单数据
    getFrom: function () {
        return util.getFromData()
    },
    // 判断表单数据是否合格
    checkFrom: function (data) {
        for (const key in data) {
            if (data[key] === '') {
                diaLog('数据不能为空')
                return false
            }
        }
        return true
    },
    // 提交表单
    submitFrom: function (callback) {
        let self = registary;
        let form = self.getFrom()
        if (!self.checkFrom(form)) return
        $.ajax({
            type: "POST",
            datatype: "JSON",
            url: base + '/user/registary',
            data: {
                username: form.user,
                password: form.psw
            },
            success: function (msg) {
                if (msg.data === null || msg.msg) {
                    diaLog(msg.msg)
                } else {
                    route.back(removePage, 'login')
                }
            }
        })
    }
}

// 登录
const login = {
    // 获取表单数据
    getFrom: function () {
        return util.getFromData()
    },
    // 判断表单数据是否为空
    checkFrom: function (data) {
        for (const key in data) {
            if (data[key] === '') {
                diaLog('数据不能为空')
                return false
            }
        }
        return true
    },
    // 提交表单
    submitFrom: function () {
        let form = this.getFrom()
        if (!this.checkFrom(form)) return
        $.ajax({
            type: 'POST',
            datatype: 'JSON',
            url: base + '/user/login',
            data: {
                username: form.user,
                password: form.psw
            },
            success: function (msg) {
                let status = msg.status;
                if (status === 200) {
                    localStorage.setItem('token', `Bearer ${msg.data.token}`)
                    route.back(removePage, 'login')
                } else if (msg.msg && status === 401) {
                    diaLog(msg.msg)
                }
            }

        })
    }
}

// 路由
const route = {
    page: '',
    // forward back
    direction: '',
    init: function () {
        route.hashchange();
        document.body.onload = function() {
            location.hash = ''
        }
        // const e = new Event('hashchange');
        // window.dispatchEvent(e)
    },
    back: function (callback, clas) {
        this.direction = 'back'
        history.back()
        callback(clas)
    },
    hashchange: function () {
        const self = this;
        window.addEventListener('hashchange', function () {
            let hash = location.hash.slice(1);
            if (hash === '') {
                hash = 'index'
            }
            if(this.direction == 'back') {
                return $(`.${self.page}`).eq(0).remove();
            }
            self.direction = 'forward'
            const path = {
                login: function () {
                    self.page = 'login'
                    templa('登录', 'login')
                },
                sign: function () {
                    self.page = 'sign'
                    templa('注册', 'sign')
                },
                edit: function () {
                    self.page = 'edit'
                    if (util.getSession()) {
                        templateExport['Uploader'](function(id) {
                            edit.init(id);
                        });
                    } else {
                        diaLog('请选择修改列表')
                        history.back()
                    }
                },
                add: function () {
                    self.page = 'edit'
                    console.log('添加');
                    templateExport['Uploader'](function(id) {
                        edit.init(id);
                    });
                },
                index: function () {
                    self.page = 'index'
                    index.getLists()
                }
            } [hash]();

        })

    }
}

// 首页
const index = {
    page: 1,
    pageSize: 12,
    lists: [],
    getToken: function () {
        return localStorage.getItem('token')
    },
    loading: true,
    init: function () {
        this.getLists()
        this.scrollBottom()
    },
    getLists: function () {
        let flag = index.getToken()
        if (!flag) return
        index.buttonHide(flag)
        $.ajax({
            url: base + '/tour/lists',
            type: 'GET',
            dataType: 'JSON',
            data: {
                page: this.page,
                pageSize: this.pageSize
            },
            headers: {
                authorization: this.token
            },
            success: function (msg) {
                this.loading = true;
                this.loadingToast(this.loading)
                if (msg.data.length === 0) {
                    diaLog('已经到底了')
                } else {
                    this.lists = this.lists.concat(msg.data);
                    this.render(msg.data)
                }

            }.bind(this)
        })
    },
    render: function (lists) {
        $('.weui-panel__bd').html('')
        let fragment = new DocumentFragment();
        $('#LoginToRemind').hide()
        lists.forEach(function (el, i) {
            let link = el.link;
            let time = new Date(el.createTime).Format("yyyy-MM-dd");
            el.time = time;
            let a = document.createElement('a')
            a.className = 'weui-media-box weui-media-box_appmsg';
            a.href = link;
            let html = template('newList', el)
            a.innerHTML = html;
            fragment.append(a)
        });
        $('.weui-panel__bd').append(fragment)
    },
    // 滚动加载
    scrollBottom: function () {
        $(window).scroll(function () {
            let top = $(window).scrollTop(); // scrollTop
            let height = $(window).height(); // window.innerHeight
            let tall = $(document).height();// scrollHeight
            if (top + height >= tall - 10) {
                if (index.loading) {
                    index.loading = false
                    index.page++;
                    index.loadingToast(index.loading)
                    index.getLists()
                }
            }
        })
    },
    // 登录状态隐藏按钮
    buttonHide: function (flag) {
        if (flag) {
            $('#btn').hide()
        } else {
            $('#btn').show()
        }
    },
    // 加载操作提示
    loadingToast: function (bool) {
        if (!bool) {
            $('#loadingToast').show()
        } else {
            $('#loadingToast').hide()
        }
    }
}

// batch 
const batch = {
    state: false,
    init: function () {
        $('#control').on('click', this.toggleCheck)
        $('#del').on('click', this.removeList)
        $('.weui-panel__bd').on('change', '.check', this.saveSession)
    },
    showCheck: function () {
        $('.check').show()
    },
    hideCheck: function () {
        $('.check').hide()
        $('.check').prop("checked", false)
        this.clearSession()
    },
    toggleCheck: function () {
        batch.state = !batch.state;
        if (batch.state) {
            batch.showCheck()
        } else {
            batch.hideCheck()
        }
    },
    getDeleteID: function () {
        return $('.check:checked').attr('data-id');
    },
    removeList: function () {
        let id = batch.getDeleteID();
        if (id) {
            $.ajax({
                url: base + '/tour/delete',
                type: 'delete',
                dataType: 'JSON',
                data: {
                    id: id
                },
                headers: {
                    authorization: localStorage.getItem('token')
                },
                success: function (msg) {
                    popup()
                    index.getLists()
                }
            })
        } else {
            diaLog('你还没有勾选列表')
        }
    },
    // 保存属性到session
    saveSession: function () {
        let dataObj = {}
        let id = $(this).data('id');
        const target = index.lists.find(function(el){
            return el.id == id
        })
        // dataObj.title = parent.find('.weui-media-box__title').html();
        // dataObj.desc = parent.find('.weui-media-box__desc').html();
        // dataObj.creatObj = parent.find('.weui-media-box__info__meta').html();
        // dataObj.creatObjTime = parent.find('#time').html();
        // dataObj.url = parent.find('.weui-media-box__thumb').attr('src')
        sessionStorage.setItem('dataObj', JSON.stringify(target))
    },
    // 清除session
    clearSession: function () {
        sessionStorage.clear()
    }
}

// 上传
const edit = {
    id: '',
    upload: function (img, cb) {
        const params = new FormData();
        params.append('file', img)
        $.ajax({
            contentType: false,
            // 不让ajax 序列化数据
            processData: false,
            url: '/tour/upload',
            type: 'POST',
            dataType: 'JSON',
            data: params,
            headers: {
                authorization: localStorage.getItem('token')
            },
            success: function (msg) {
                if (msg.status === 200) {
                    console.log(msg)
                    cb( msg.data.path)
                }
            }
        })
    },
    // edit.init
    init: function(id) {
        this.id = id;
        // 清除session
        util.clearSession();
        // 事件绑定
        $('#uploaderInput').on('change', this.inputChange.bind(this))
        $('#back').on('click', function () {
            route.back(removePage, 'edit')
            index.getLists()
        })
        $('#editSubmit').click(this.submitForm.bind(this))
    },
    inputChange: function(e) {
        const fileObj = e.target.files[0];
        // let img = new Image()
        const src = URL.createObjectURL(fileObj)
        this.uploadImgReplace(src)
        // img.src = URL.createObjectURL(fileObj)
        // img.onload = function() {
        //     this.uploadImgReplace()
        // }
    },
    uploadImgReplace: function (path) {
        $('.weui-uploader__file').css({
            'backgroundImage': `url(${path})`
        })
        $('.weui-icon-warn').hide()
    },
    getForm: function() {
        return {
            title: $('#title').val(),
            description: $('#description').val(),
            img: $("#uploaderInput")[0]
        }
    },
    checkForm: function(form) {
        if(!form.title || !form.description || !form.img.files.length) {
            console.log('请填写完整！');
            return false
        }
        return true
    },
    submitTour: function(form) {
        if(this.id) {
            form.id = this.id;
        }
        Object.assign(form, {
            tag:'旅游',
            link: 'https://www.baidu.com'
        })
        $.ajax({
            url: `/tour/${this.id ? 'update' : 'add'}`,
            type:'POST',
            dataType: 'JSON',
            data: form,
            headers: {
                authorization: localStorage.getItem('token')
            }
        }).then(res => {
           console.log(res,'res');
        })
    },
    submitForm: function () {
        const form = this.getForm();
        if(!this.checkForm(form)) {
            return 
        }
        const self = this;
        this.upload(form.img.files[0], function(picPath) {
            form.img = picPath
            self.submitTour(form);
        })
    }
}

// 模板
const templateExport = {
    Uploader: function (cb) {
        let data = util.getSession() || {};
        let html = template('Uploader', data)
        let dome = document.createElement('div');
        dome.id = 'edit';
        dome.className = 'edit';
        dome.innerHTML = html
        document.body.append(dome);
        cb(data.id);
    }
}
// 模板
function templa(id, cla) {
    let data = {
        id: id,
        name: cla
    }
    let html = template('loginTpl', data)
    // document.body.append($(html)[0])
    $('body').append($(html))
    // $(html).appendTo($('body'))

    // 事件绑定
    $('#back').on('click', function () {
        route.back(removePage, 'login')
    })
    // 登录
    $('#login') && $('#login').on('click', function () {
        login.submitFrom()
    })
    // 注册
    $('#sign') && $('#sign').on('click', function () {
        registary.submitFrom()
    })
}


// 删除当前页面
const removePage = function (cla) {
    let dom = $('.' + cla)
    dom.remove()
    popup()
}

// 用户操作提示
// 操作失败弹窗
const diaLog = function (msg) {
    let Dialog = $('#Dialog');
    Dialog.show();
    Dialog.find('.weui-dialog__title').html(msg)
    Dialog.find('.weui-dialog__bd').html(msg)
}

// 关闭弹窗
$('.weui-dialog__btn').on('click', function () {
    $('#Dialog').hide();
})

// 操作成功弹窗
function popup() {
    let Dialog = $('#toast')
    Dialog.show()
    setTimeout(function () {
        Dialog.hide()
    }, 800)
}

// 返回
function comingBack() {
    $('.login').remove()
    history.back()
}

// 工具函数
const util = {
    // 获取表单数据
    getFromData: function () {
        let data = {};
        $('.weui-input').each(function (i, el) {
            let key = $(el).attr('name')
            data[key] = $(el).val()
        })
        return data
    },
    // 判断hash是否为edit
    regHase: function (hash) {
        let reg = /^edit/;
        return reg.test(hash)
    },
    // 获取session
    getSession: function () {
        let data = sessionStorage.getItem('dataObj')
        if (data) {
            return JSON.parse(data)
        }
    },
    // 清除session
    clearSession: function () {
        sessionStorage.clear()
    }
}

// 格式化时间
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// 初始化
route.init()
index.init()
batch.init()